package com.admin.system.controller;

import com.admin.system.service.MinioService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.system.service.dto.DeptDto;
import me.zhengjie.modules.system.service.dto.DeptQueryCriteria;
import me.zhengjie.utils.PageUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Nullable;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 附件上传
 * @author: shujh
 * @date: 2021/8/7
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "Minio附件上传")
@RequestMapping("/api/upload")
public class UploadController {

    @Resource
    private MinioService minioService;

    @Log("单附件上传")
    @ApiOperation("单附件上传")
    @PostMapping("/singleUpload")
    public ResponseEntity<Object> singleUpload(@Nullable MultipartFile file) throws Exception {
        JSONObject result = new JSONObject();
        try
        {
            String fileUrl = minioService.saveImg(file);
            result.put("fileUrl", fileUrl);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            result.put("errMsg", ex.getMessage());
        }
        result.put("success", !result.containsKey("errMsg"));
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @Log("多附件上传")
    @ApiOperation("多附件上传")
    @PostMapping("/multiUpload")
    public ResponseEntity<Object> multiUpload(@Nullable MultipartFile[] files) throws Exception {
        JSONObject result = new JSONObject();
        assert files != null;
        JSONArray array = new JSONArray();
        Arrays.stream(files).forEach(file -> {
            try {
                JSONObject fileInfo = new JSONObject();
                fileInfo.put("originalFileName", file.getOriginalFilename());
                String fileUrl = minioService.saveImg(file);
                fileInfo.put("fileUrl", fileUrl);
                array.add(fileInfo);
            } catch (Exception e) {
                e.printStackTrace();
                result.put("errMsg", e.getMessage());
            }
        });
        result.put("fileArray", array);
        result.put("success", !result.containsKey("errMsg"));
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

}
